<template>
  <div class="the-list">

    <div class="panel-table">
      <div class="table-head">
        <div>
          打赏物品列表
        </div>
        <div>
          <el-button type="primary" @click="sortFn.openPanel">排序</el-button>
          <el-button type="primary" @click="operateFn.openPanel('add')">新增</el-button>
        </div>
      </div>

      <el-table :data="table.list" stripe :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" style="width: 100%;" border>
        <el-table-column prop="sort" label="排序" width="80px"/>

        <el-table-column prop="name" label="物品名称" />
        <el-table-column prop="cost" label="物品价值/小饼干" />
        <el-table-column prop="imageUrl" label="图标" width="106px">
          <template #default="{row}">
            <div v-if="row.imageUrl" @click="imageViewer({initialIndex: 0,urlList: [row.imageUrl]});">
              <el-image style="width: 80px;height: 45px;display:block;" fit="contain" :src="row.imageUrl"/>
            </div>
            <p v-else>--</p>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="已打赏次数" />

        <el-table-column fixed="right" label="操作" width="80px">
          <template #default="{row}">
            <el-button size="small" type="primary" plain @click="operateFn.openPanel('edit',row)">编辑</el-button>
            <!-- <el-button v-if="row.status === 0" size="small" type="success" plain>上架</el-button>
            <el-button v-else size="small" type="warning" plain>下架</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <div class="table-pagination">
        <pagination :total="table.total" v-model:page="table.query.page" v-model:limit="table.query.pageSize" @pagination="tableFn.getTableData" />
      </div>

    </div>

    <el-dialog title="物品配置排序" v-model="sort.showPanel" width="50%" :close-on-click-modal="false" :before-close="sortFn.closePanel">
      <div class="panel-table">

        <el-table :data="sort.list" stripe :header-cell-style="{backgroundColor:'#ededed',padding:'12px 0'}" style="width: 100%;" border>
          <el-table-column prop="sort" label="排序" width="180px">
            <template #default="{row}">
              <el-input-number v-model="row.sort" :max="9999" :min="0" controls-position="right" @change="sortFn.sortChange($event,row.id)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="物品名称" />
          <el-table-column prop="imageUrl" label="物品图片" width="106px">
            <template #default="{row}">
              <div v-if="row.imageUrl" @click="imageViewer({initialIndex: 0,urlList: [row.imageUrl]});">
                <el-image style="width: 80px;height: 45px;display:block;" fit="contain" :src="row.imageUrl"/>
              </div>
              <p v-else>--</p>
            </template>
          </el-table-column>
        </el-table>

      </div>
      <div class="table-foot" style="margin: 12px;text-align:right;">
        <el-button type="primary" plain @click="sortFn.closePanel">取消</el-button>
        <el-button type="primary" :disabled="sort.postMap.size===0" @click="sortFn.submitData">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="新增/编辑" v-model="operate.showPanel" width="70%" :close-on-click-modal="false" :before-close="operateFn.closePanel">
          
        <el-form v-loading="operate.isLoading" ref="formRef" :rules="formRules" :model="operate.post" class="demo-form-inline" label-width="140px">

          <el-form-item prop="name" label="物品名称">
            <el-input v-model="operate.post.name" style="max-width:420px;" placeholder="物品名称"></el-input>
          </el-form-item>
          <el-form-item prop="cost" label="物品价值">
            <el-input-number v-model="operate.post.cost" style="max-width:420px;" :min="0" controls-position="right" placeholder="物品价值"></el-input-number>
          </el-form-item>

          <el-form-item prop="imageUrl" label="物品图片">
            <inputUpload v-model="operate.post.imageUrl"></inputUpload>
          </el-form-item>

          <el-form-item style="text-align:center">
            <el-button type="primary" plain @click="operateFn.closePanel">取消</el-button>
            <el-button type="primary" plain @click="operateFn.submitPre(formRef)">提交</el-button>
          </el-form-item>
        </el-form>

    </el-dialog>

  </div>
</template>

<script setup>
import { reactive, ref, watchEffect } from "vue";

import { getRewardConfiglist,modifyRewardConfigSort,modifyRewardConfig,addRewardConfig } from "@/api/config";
import { ElMessage, ElMessageBox } from "element-plus";
import Pagination from "@/components/Pagination";
import { useRouter } from "vue-router";
import { configList,getItemFromArray,isLongTime } from "@/utils/tool";
import imageViewer from "@/components/imageViewer/index2";

const router = useRouter();

const params = ref({});
const query = ref({});

const formRef = ref();
const formRules = reactive({
  name: [{ required: true, message: "请填写物品名称", trigger: "blur" }],
  cost: [{ required: true, message: "请填写物品价值", trigger: "blur" }],
  imageUrl: [{ required: true, message: "请填写或上传图片", trigger: "blur" }],
});

watchEffect(()=>{
  params.value = router.currentRoute.value.params;
})
watchEffect(()=>{
  query.value = router.currentRoute.value.query;
})

// 评论的表格功能模块，包括搜索，分页和表格体等
const { $data: table, $fn: tableFn } = (() => {
  const router = useRouter();
  const backup = {
    query: {
      pageSize: 10,
      page: 1,
    },
  };

  const $data = reactive({
    query: { ...backup.query },
    list: [],
    total: 0,
  });
  const $fn = {
    getTableData() {
      getRewardConfiglist($data.query).then((res) => {
        if (res.code === 0) {
          $data.list = res.data.items;
          $data.total = res.data.pagination.total_record;
        }
      });
    },
    onResetQuery() {
      $data.query = { ...backup.query };
      $fn.getTableData();
    },
    onSubmit() {
      $fn.getTableData();
    },
  };
  $fn.getTableData();
  return {
    $data,
    $fn,
  };
})();
// 回复的表格模块，包括分页和表格体
const { $data: sort, $fn: sortFn } = (() => {
  const $static = {
    listData: [],//列表数据备份
  }
  const $data = reactive({
    showPanel: false,
    hasModify: false,
    postMap: new Map(),
    list: [],
    
  });
  const $fn = {
    getTableData() {
      getRewardConfiglist({page:1,pageSize:table.total}).then((res) => {
        if (res.code === 0) {
          $data.list = res.data.items;
          $static.listData = JSON.parse(JSON.stringify(res.data.items||[]));
        }
      });
    },
    openPanel() {
      $data.showPanel = true;
      $data.hasModify = false;
      $fn.getTableData();
    },
    closePanel() {
      $data.showPanel = false;
      $data.list = [];
      $static.listData = [];
    },
    sortChange(sort,id){
      console.log($static.listData);
      let oValue = getItemFromArray( $static.listData,id,{key:"id",name:"sort"});
      if(sort === oValue){
        $data.postMap.delete(id);
      }else{
        $data.postMap.set(id,{sort,id});
      }
    },
    submitData(){
      let req = [
        ...$data.postMap.values(),
      ]
      console.log("update sort:",req);
      modifyRewardConfigSort(req).then(res=>{
        if(res.code===0){
          ElMessage.success("修改成功！");
          tableFn.getTableData();
          $fn.closePanel();
        }
      })
    }
  };
  return {
    $data,
    $fn,
  };
})();
// 新增、编辑
const { $data: operate, $fn: operateFn } = (() => {
  const $static = {
    post: {
      name: "",//名字
      cost: undefined,//价值
      imageUrl: "",//图片地址
    },
  }
  const $data = reactive({
    showPanel: false,
    isEdit: false,
    isLoading: false,
    post: {...$static.post},
  });
  const $fn = {
    openPanel(type,row){
      if(type==='edit'){
        $data.isEdit = true;
        $data.post = {...row};
      }else{
        $data.isEdit = false;
      }
      $data.showPanel = true;
    },
    closePanel(){
      console.log("close panel!");
      $data.showPanel = false;
      $data.post = {...$static.post};
      $data.isLoading = false;
      formRef.value.resetFields();
    },
    submitPre(formRef){
      if (!formRef) return;
      formRef.validate((valid) => {
        if (valid) {
          $fn.submitData();
        }
      });
    },
    submitData(){
      // $data.isLoading = true;
      let req = {
        ...$data.post,
      }
      console.log("req:",req);
      // return;
      $data.isLoading = true;
      if($data.isEdit){
        modifyRewardConfig(req).then(res=>{
          if(res.code===0){
            ElMessage.success("修改成功！");
            $fn.closePanel();
            tableFn.getTableData();
          }
        })
      }else{
        addRewardConfig(req).then(res=>{
          if(res.code===0){
            ElMessage.success("添加成功！");
            $fn.closePanel();
            tableFn.getTableData();
          }
        })
      }
    },
  };
  return {
    $data,
    $fn,
  };
})();
</script>

<style scoped lang="scss">
@import "@/styles/tablePage.scss";
</style>